import { getToken, setToken, removeToken } from '@/utils/auth'
import { loginApi, getUserInfoApi } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router/index'
const state = {
  token: getToken(),
  userInfo: {},
  routes:[...constantRoutes]
}
const mutations = {
  updateToken(state, token) { 
    state.token = token
    setToken(token)
  },
  delToken(state) {
    state.token = null
    removeToken()
  },
  updateUserInfo(state,data) {
    state.userInfo = data
  },
  getRoutes(state, payload) {
    state.routes = [...constantRoutes, ...payload]
  }
}
const actions = {
  async login(context, data) {
    const res = await loginApi(data)
    context.commit('updateToken', res)
  },
  async getUserInfo(context) {
    const res = await getUserInfoApi()
    context.commit('updateUserInfo', res)
    return res
  },
  logout(context) {
    context.commit('delToken')
    context.commit('updateUserInfo', {})
    resetRouter()
  }
}
export default {
   namespaced: true,
   state,
   mutations,
   actions
}